import $ from 'jquery';

export var HttpClient = (function () {
    var REQUEST = "truth";

    var requestSuccess = 0;
    var requestDataError = 1;
    var requestServiceError = 2;

    //获取请求host
    // var httpClientHost = 'http://guowenjun.top/';
    var httpClientHost = 'http://127.0.0.1:3000/';
    function query(url, rtype, data, callback = function () { }) {
        return () => {
            return new Promise(function (resolve, reject) {
                let httpUrl = ''
                if (url.indexOf("http") != -1) {
                    httpUrl = url
                } else {
                    httpUrl = httpClientHost + url
                }
                let headers = null;
                $(function () {
                    $.ajax({
                        "url": httpUrl,
                        "headers": headers,
                        "contentType": 'application/json; charset=utf-8',
                        "method": rtype,
                        "cache": true,
                        "async": true,
                        "data": rtype === 'post' ? JSON.stringify(data) : data,
                        success: function (d) {
                            console.log(d)
                            resolve(d)
                        },
                        error: function (e) {
                            // return e
                            //服务异常
                            console.error(REQUEST + "--" + url + "--Error:", e);
                            callback(e, requestServiceError);
                            reject(e)
                        }
                    });
                })
            })
        }
    }

    return {
        ClientHost: httpClientHost,
        GET: 'GET',
        POST: "POST",
        PUT: "PUT",
        DELETE: "DELETE",
        requestSuccess: requestSuccess,
        requestDataError: requestDataError,
        requestServiceError: requestServiceError,
        query: query,
        REQUEST: REQUEST
    }


}());
